<template>
  <view class="steps" :class="[`steps--${direction}`]">
    <slot />
  </view>
</template>

<script lang="ts">
import getCurrentComponent from '@/utils/get-current-component'
import { defineComponent, provide, watch, reactive, toRefs } from '@vue/composition-api'

export default defineComponent({
  props: {
    direction: {
      type: String,
      default: 'horizontal',
    },
    current: {
      type: [String, Number],
      default: 0,
    },
    textAlign: {
      type: String,
      default: 'left',
    },
    space: {
      type: Number,
      default: 30,
    },
  },
  setup(props) {
    const vm: any = getCurrentComponent()
    const state = reactive({
      stepList: [] as any[],
    })

    provide('stepParent', {
      stepList: state.stepList,
      direction: props.direction,
      textAlign: props.textAlign,
      space: props.space,
      addStep(step) {
        state.stepList.push(step)
        // init
        step.vm.setStep(step.label, props.current)

        vm.$nextTick(() => {
          step.vm.setFirstAndList(step.label, state.stepList)
        })
      },
      removeStep(label) {
        const index = state.stepList.findIndex((x) => x.label === label)

        state.stepList.splice(index, 1)
      },
    })

    watch(
      () => props.current,
      (newVal) => {
        state.stepList.forEach((step) => {
          step.vm.setStep(step.label, newVal)
        })
      }
    )

    return {
      ...toRefs(state),
    }
  },
})
</script>
<style lang="scss" scoped>
.steps {
  width: 100%;
  &--horizontal {
    display: flex;
    flex-direction: row;
  }
}
</style>
